<?php
namespace app\common\controller;

use app\common\model\AuthGroup;
use app\common\model\AuthRule;
use app\common\model\User;
use app\common\model\Menu;
use app\common\controller\Base;

use think\Request;


class Admin extends Base
{
    use \app\common\traits\Curd;
    
    protected $modelClass=null;
    
    protected $serviceClass = null;

    protected $authenticate; // 身份验证
    
    protected function _initialize(){
        
        //定义model
        if ($this->modelClass == null) {
            $this->modelClass = 'app\common\model\\'.ucfirst(preg_replace('/[^>]+\./','',Request::instance()->controller()));//默认model
        }
    
//        if ($this->logicClass == null) {
//            $this->logicClass = 'app\common\logic\\'.ucfirst(preg_replace('/[^>]+\./','',\Request::controller()).'Logic');//默认logic
//        }
//
//        if ($this->serviceClass == null) {
//            $this->serviceClass = 'app\common\logic\\'.ucfirst(preg_replace('/[^>]+\./','',\Request::controller()).'Service');//默认service
//        }
        

        //指定哪些方法需要登陆，后面要替换掉auth
        if ($this->authenticate) {
            $this->beforeActionList['authenticate'] = $this->authenticate;
        } else {
            $this->beforeActionList['authenticate'] = null;//为null的话默认所有接口都要权限
        }
        
        $user = session('ke_user_auth');
        $this->assign('real_name',$user['real_name']);
        
        //只检测已经设置的权限，还有ajax之外的东西
        if($this->isRule()&&!Request::instance()->isAjax()){
            
            $user = session('ke_user_auth');
            if($user['username']!='admin'){
                //权限认证
                $auth=new \Auth\Authorization();//权限认证Auth类
                if(!$auth->check(strtolower(\Request::module().'/'.\Request::controller().'/'.\Request::action()),SID)){
                    echo '没有权限';die;

                }
            }
            
        }

        //菜单
        $this->menu();
        
    }
    
    /**
     *  鉴定身份
     */
    protected function authenticate()
    {
//        $request = Request::instance();
        define('SID', is_login());
        if (!SID&&strtolower(request::instance()->controller())!='manager') {
            
            $this->error('需要登录','/manager/login');
        }
        
    }
    
    protected function isRule(){
//        $request = Request::instance();
        $tempStr = strtolower(request::instance()->module().'/'.request::instance()->controller().'/'.request::instance()->action());
        
        $isHas = AuthRule::get(['name'=>$tempStr]);
        
        if($isHas){
            return true;
        }else{
            return false;
        }
    }

    
    
    protected function menu(){
       
        $menuList = Menu::all(function($query){
            $query->where('parent_id', 0)->order('sort', 'desc');
        });
        
        $tempArr = array();
        foreach ($menuList as $index=>$menu){
            
            $menu['child'] = Menu::where('parent_id',$menu->id)->order('sort', 'desc')->select();
            $menu['child_count'] = count($menu['child']);
            array_push($tempArr,$menu);
            
        }
        
        $this->assign('menuList', $tempArr);//后台菜单
       
        
    }
    
    protected function recursion($menuList,$menu){
        $menu->child = array();
        foreach ($menuList as $key=>$value){
            if($value->parent_id==$menu->id){
                $child= $this->recursion($menuList,$value);
                array_push($menu->child,$value);
            }
        }
        return $menu;
    }
    
    //权限
    public function rule(){
        if(Request::instance()->isAjax()){
            $Auth_rule=new AuthRule();
            $rulelist=$Auth_rule->getRuleList();
            return json($rulelist);
        }
        return view('rule');
    }
    
    //修改权限
    public function ruleUp(){
        if(Request::instance()->isAjax()){
            $rule=input('post.rule/a');
            if(empty($rule['name'])){
                return array('status'=>'erro','msg'=>'更新失败,权方法名不能为空');
            };
            if(empty($rule['title'])){
                return array('status'=>'erro','msg'=>'更新失败,权限名不能为空');
            }
            $Auth_rule=new AuthRule();
            $result=$Auth_rule->update($rule);
            if($result===false){
                return array('status'=>'erro','msg'=>'更新失败');
            }
            return array('status'=>'success','msg'=>'更新成功');
        }
    }
    
    //启禁用权限
    public function ruleStatusUp(){
        $rule=input('rule/a');
        if($rule['status']==='false'){
            $rule['status']=0;
        }
        if($rule['status']==='true'){
            $rule['status']=1;
        }
        $Auth_rule=new AuthRule();
        $result=$Auth_rule->update($rule);
        if($result===false){
            return array('status'=>'erro','msg'=>'状态修改失败');
        }
        return array('status'=>'success','msg'=>'更新成功');
    }
    
    //添加权限
    public function ruleAdd(){
        if(Request::instance()->isAjax()){
            $rule=input('rule/a');
            if(empty($rule['name'])){
                return array('status'=>'error','msg'=>'添加失败,规则不能为空！');
            };
            if(empty($rule['title'])){
                return array('status'=>'error','msg'=>'添加失败,规则名不能为空！');
            }
            $Auth_rule=new AuthRule();
            $result=$Auth_rule->data($rule)->save();
            if($result){
                $rulelist=$Auth_rule->getRuleList();
                return array('status'=>'success','data'=>$rulelist);
            }
            return array('status'=>'erro','msg'=>'添加失败');
            
        }
    }
    
    
    //用户
    public function user(){
        if(Request::instance()->isAjax()){
            $User=new User();
            $arr=$User->getUserList();
            return json($arr);
        }
        return view('user');
    }
    //更该用户信息
    public function userUp(){
        if(Request::instance()->isAjax()){
            $user=input('user/a');
            $admin_user = session('ke_user_auth');
            Db::startTrans();
            try{
                Db::name('Auth_group_access')->where(array('uid'=>$user['admin_id']))->update(array('group_id'=>$user['group_id']));
                $data=array('password'=>$user['password'],'handler'=>$admin_user['account'],'update_time'=>time());
                Db::name('User')->where(array('admin_id'=>$user['admin_id']))->update($data);
                Db::commit();
                $User=new User();
                $arr=$User->getUserList();
                return array('status'=>'success','data'=>$arr);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return array('status'=>'error','msg'=>'保存失败！');
            }
        }
    }
    
    
    /**
     * 模板变量赋值
     */
    protected function setAssign($signArr = [])
    {
        
        foreach ($signArr as $k => $v) {
            $this->assign($k, $v);
        }
    }
    
    /**
     * 查- 列表
     * @return string
     */
    public function index()
    {
        
        $list = $this->prepareDataProvider();
        $p = $list->toArray();
        $this->assign('total', $p['total']);
        $this->assign('perPage', $p['per_page']);
        $this->assign('currentPage', $p['current_page']);
        $this->assign('list', $list);
        
        return $this->fetch();
    }
    
    

    /**
     * 增- 表单
     * @return string
     */
    public function add()
    {
        return $this->fetch();
    }

    
    /**
     * 增 - 确认保存
     * @return string
     */
    public function save()
    {
        $modelClass = $this->modelClass;
        $model = new $modelClass($_POST);
        // 过滤post数组中的非数据表字段数据
        $model->allowField(true)->save();
        if ($model) {
            
            $this->success("新增成功！", 'index');
        } else {
            $this->error("新增失败！");
        }


    }

    /**
     * 改 - 表单
     * @param $id
     * @return string
     */
    public function edit($id)
    {

        $model = $this->findModel($id);
        $this->assign('model', $model);
        return $this->fetch();
    }

    /**
     * 改 - 确认修改
     * @param $id
     * @return string
     */
    public function update($id)
    {
        $model = $this->findModel($id);
        $rt = $model->allowField(true)->save(paramFormPost(),['id'=>$id]);
        if ($rt) {
            $this->success("更新成功！", "index");
        } else {
            $this->error("更新失败!");
        }
    }

    /**
     * 删除 - 不是真的删除，而是修改状态而已。
     * @param $id
     * @return string
     */
    public function delete($id)
    {
        $model = $this->findModel($id);
        if(!isset($model->flag)){
            $this->error('该表没有flag字段');
        }
        $params = ['flag'=>0];
        $rt = $model->allowField(true)->save($params,['id'=>$id]);

        if ($rt) {
            $this->success("删除成功！");
        } else {
            $this->error("删除失败!");
        }
    }


    /**
     * 删，这是真的删了。。。
     * @param $id
     * @return string
     */
    public function destory($id)
    {

        $model = $this->findModel($id);
       
        $rt = $model->delete();
        if ($rt) {
            $this->success("删除成功！", "index");
        } else {
            $this->error("删除失败！");
        }

    }
    
    /**
     * 重写 表单验证
     */
    protected function validate($data, $validate, $message = [], $batch = false, $callback = null)
    {
        $result = parent::validate($data, $validate, $message, $batch, $callback); // TODO: Change the autogenerated stub
        if (true !== $result) {
            $this->error($result);
        }
    }
    
    
    
    
    
    
}
